package bx.com.smartcashier.view;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSONArray;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import bx.com.smartcashier.R;
import bx.com.smartcashier.activity.CashRegisterSucessedActivity;
import bx.com.smartcashier.config.ServerUrl;
import bx.com.smartcashier.mode.GoodsDetailVO;
import bx.com.smartcashier.mode.GoodsUp;
import bx.com.smartcashier.mode.SmartShopOrderVO;
import bx.com.smartcashier.utils.JsonUtils;

/**
 * 底部弹窗Fragment
 */
public class PayDetailFragment extends DialogFragment {
    private RelativeLayout rePayDetail, reZfb,reCancle,reCash,reWx,reBank;
    private LinearLayout LinPayWay;
    ArrayList<GoodsDetailVO> rs;
    private String totalPrice;
    private TextView tvPayWay;
    private ListView lvPays;
    private BaseAdapter adapter;
    private Button btnSurePay;
    private String token;
    private Integer  warehouseId;
    private Integer shopId;
    private String payType;
    private TextView tvTotalPrice;
    private ImageView ivDismiss;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
        Dialog dialog = new Dialog(getActivity(), R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.fragment_pay_detail);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        final Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.AnimBottom);
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        lp.height = getActivity().getWindowManager().getDefaultDisplay().getHeight() * 2 / 5;
        window.setAttributes(lp);
        rs=getArguments().getParcelableArrayList("rs")  ;
        totalPrice=getArguments().getString("totalPrice");
        rePayDetail = (RelativeLayout) dialog.findViewById(R.id.re_pay_detail);//付款方式
        LinPayWay = (LinearLayout) dialog.findViewById(R.id.lin_pay_way);//最终结算页面
        reCancle = (RelativeLayout)dialog.findViewById(R.id.re_cancle);//取消
        reCash=(RelativeLayout)dialog.findViewById(R.id.re_cash);//现金
        reZfb=(RelativeLayout)dialog.findViewById(R.id.re_zfb);//支付宝
        reWx=(RelativeLayout)dialog.findViewById(R.id.rl_wx);//微信
        reBank=(RelativeLayout)dialog.findViewById(R.id.rl_bank);//银行卡
        tvPayWay=(TextView)dialog.findViewById(R.id.tv_pay_way);//确认支付方式
        lvPays=(ListView)dialog.findViewById(R.id.lv_pays);//确认支付产品list
        btnSurePay=(Button)dialog.findViewById(R.id.bt_sure_pay);//确认支付


        ivDismiss=(ImageView)dialog.findViewById(R.id.iv_dismiss);
        tvTotalPrice=(TextView)dialog.findViewById(R.id.tv_total_price);//总价格

        reCash.setOnClickListener(listener);
        reCancle.setOnClickListener(listener);
        reZfb.setOnClickListener(listener);
        reWx.setOnClickListener(listener);
        reBank.setOnClickListener(listener);
        btnSurePay.setOnClickListener(listener);
        ivDismiss.setOnClickListener(listener);
        initDatas();
        return dialog;
    }

    /**
     * 初始化数据
     */
    private void initDatas() {
        getShopList();
        SharedPreferences sharedPreferences =getActivity().getSharedPreferences("User",0);
        token = sharedPreferences.getString("token","null");
        adapter=new BaseAdapter(){

            @Override
            public int getCount() {
                return rs.size();
            }

            @Override
            public GoodsDetailVO getItem(int position) {
                return rs.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                final GoodsDetailVO one = getItem(position);
                View view;
                ViewHolder viewHolder;

                if (convertView == null){
                    // inflate出子项布局，实例化其中的图片控件和文本控件
                    view = LayoutInflater.from(getActivity()).inflate(R.layout.sure_pay_item, null);

                    viewHolder = new ViewHolder();
                    // 通过id得到图片控件实例
                    viewHolder.goodsName = (TextView) view.findViewById(R.id.tv_goods_name);
                    // 通过id得到文本空间实例
                    viewHolder.goodsBuyCount = (TextView) view.findViewById(R.id.tv_goods_buy_count);

                    view.setTag(viewHolder);
                }else{
                    view = convertView;
                    // 取出缓存
                    viewHolder = (ViewHolder) view.getTag();
                }

                viewHolder.goodsName.setText(one.getGoodsName());
                // 文本控件设置文本内容
                viewHolder.goodsBuyCount.setText("x"+one.getBuyCount());


                return view;
            }
            // 内部类
            class ViewHolder{
                TextView goodsName;
                TextView goodsBuyCount;

            }

        };
        lvPays.setAdapter(adapter);
    }


    /**
     *
     */
    private void getShopList() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ServerUrl.url + "/sysShop/getShopList.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        s = s.replace(" ","");
                        Map<String,Object> map = JsonUtils.getMap(s);
                        if(String.valueOf(map.get("code")).equals("000000"))
                        {
                            Map<String, Object> data = JsonUtils.getMap(String.valueOf(map.get("data")));
                            List<Map<String, Object>> result = JsonUtils.getList(String.valueOf(data.get("result")));
                            warehouseId= (Integer) result.get(0).get("warehouseId");
                            shopId=(Integer) result.get(0).get("id");
                        }
                        else
                        {
                            Toast.makeText(getActivity(), "获取门店异常!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), "获取门店异常!", Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("token",token);

                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(60*1000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Animation slide_left_to_left = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_to_left);
            Animation slide_right_to_left = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_right_to_left);
            Animation slide_left_to_right = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_to_right);
            Animation slide_left_to_left_in = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_to_left_in);
            BigDecimal result=new BigDecimal("0.00");
            switch (view.getId()) {
                case R.id.re_cancle:
                    dismiss();
                    break;
                case R.id.iv_dismiss:
                    dismiss();
                    break;
                case R.id.re_zfb:
                    rePayDetail.startAnimation(slide_left_to_left);
                    rePayDetail.setVisibility(View.GONE);
                    LinPayWay.startAnimation(slide_right_to_left);
                    LinPayWay.setVisibility(View.VISIBLE);
                    tvPayWay.setText("支付宝");
                    payType="1";

                    for (int i = 0; i < rs.size(); i++) {
                        result=result.add(rs.get(i).getRetailPrice());
                    }
                    tvTotalPrice.setText("￥"+result);
                    break;
                case R.id.re_cash:
                    rePayDetail.startAnimation(slide_left_to_left);
                    rePayDetail.setVisibility(View.GONE);
                    LinPayWay.startAnimation(slide_right_to_left);
                    LinPayWay.setVisibility(View.VISIBLE);
                    tvPayWay.setText("现金");
                    payType="3";
                    for (int i = 0; i < rs.size(); i++) {
                        result= result.add(rs.get(i).getRetailPrice());
                    }
                    tvTotalPrice.setText("￥"+result);
                    break;
                case R.id.rl_wx:
                    rePayDetail.startAnimation(slide_left_to_left);
                    rePayDetail.setVisibility(View.GONE);
                    LinPayWay.startAnimation(slide_right_to_left);
                    LinPayWay.setVisibility(View.VISIBLE);
                    tvPayWay.setText("微信");
                    payType="2";
                    for (int i = 0; i < rs.size(); i++) {
                        result=result.add(rs.get(i).getRetailPrice());
                    }
                    tvTotalPrice.setText("￥"+result);
                    break;
                case R.id.rl_bank:
                    rePayDetail.startAnimation(slide_left_to_left);
                    rePayDetail.setVisibility(View.GONE);
                    LinPayWay.startAnimation(slide_right_to_left);
                    LinPayWay.setVisibility(View.VISIBLE);
                    tvPayWay.setText("银行卡");
                    payType="5";
                    for (int i = 0; i < rs.size(); i++) {
                        result=result.add(rs.get(i).getRetailPrice());
                    }
                    tvTotalPrice.setText("￥"+result);
                 break;
                case R.id.bt_sure_pay:
                    surePay();
                    break;
                default:

                    break;
            }
        }
    };

    private void surePay() {


        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ServerUrl.url + "/SmartShopOrder/insertSmartShopOrder.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        s = s.replace(" ","");
                        Map<String,Object> map = JsonUtils.getMap(s);
                        SmartShopOrderVO data=null;
                        try {
                            data = (SmartShopOrderVO) JsonUtils.toObject(String.valueOf(map.get("data")),SmartShopOrderVO.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if(String.valueOf(map.get("code")).equals("000000"))
                        {
                            Map<String,Object> map_data = JsonUtils.getMap(String.valueOf(map.get("data")));
                            Toast.makeText(getActivity(),"结算成功",Toast.LENGTH_LONG).show();
                            Intent intent=new Intent();
                            intent.setClass(getActivity(),CashRegisterSucessedActivity.class);
                            intent.putExtra("data",  data);
                            startActivity(intent);
                            getActivity().finish();
                        }
                        else
                        {
                            Toast.makeText(getActivity(), "结算失败!"+String.valueOf(map.get("msg")), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("test", "onErrorResponse: ", volleyError);
                Toast.makeText(getActivity(), "结算失败!", Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("token",token);
                map.put("amount",totalPrice);
                Integer bycount = 0;
                ArrayList<GoodsUp> goodsUps=new ArrayList<>();
                for (int i = 0; i <rs.size() ; i++) {
                    GoodsDetailVO one = rs.get(i);
                    bycount= bycount + one.getBuyCount();
                    GoodsUp goodsUp=new GoodsUp();
                    goodsUp.setGoodsDetailId(one.getGoodsDetailId()+"");
                    goodsUp.setGoodEpcid(one.getGoodsEpcid()+"");
                    goodsUp.setGoodsName(one.getGoodsName());
                    goodsUp.setWarehouseId(warehouseId+"");
                    goodsUp.setGoodsCode(one.getGoodsCode());
                    goodsUp.setCount(one.getBuyCount());
                    goodsUp.setGood_size(one.getSizeValue());
                    goodsUp.setGoodColor(one.getColorValue());
                    goodsUp.setStatus("1");
                    goodsUp.setDiscountPrice((new BigDecimal(one.getBuyCount().toString()).multiply(one.getRetailPrice())).toString());
                    goodsUp.setDiscountRate("10");
                    if(one.getUniqueCode()==null||"".equals(one.getUniqueCode())){
                        goodsUp.setCodes(one.getBarCode());
                    }else{
                        goodsUp.setCodes(one.getUniqueCode());
                    }
                    goodsUp.setRetailPrice(one.getRetailPrice().toString());
                    goodsUps.add(goodsUp);

                }
                map.put("warehouseId",warehouseId+"");
                map.put("type","1");
                map.put("smartShopOrderDetailParams", JSONArray.toJSONString(goodsUps));
                map.put("shopId",shopId+"");
                map.put("count",bycount+"");
                map.put("payType",payType);
                map.put("scanType","2");
                map.put("shoppingGuide","-1");

                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(60*1000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }
}

